//
//  SLIdentificationVC.swift
//  sulit-loan
//
//  Created by 王刚锋 on 2025/4/20.
//  Copyright © 2025 coolBoy. All rights reserved.
//

import UIKit
import ZLPhotoBrowser
import MBProgressHUD
import AVFoundation
class SLIdentificationVC: SLBaseVC, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    
    var haveCard:Bool = false
    var type:Int = 0
    var denotes:String?
    var guideTime1: Int = 0
    var guideTime2: Int = 0
    var guideTime3: Int = 0
    override func viewDidLoad() {
        guideTime1 = Int(Date().timeIntervalSince1970)
        guideTime2 = Int(Date().timeIntervalSince1970)
        guideTime3 = Int(Date().timeIntervalSince1970)
        super.viewDidLoad()
        self.title = "identification information"
        self.updateUI()
        loadData()
 
    }
    
    private lazy var topView:UIImageView  = {
        let v = create_imageView(image: IMAGE("banner"), mode: .scaleToFill, supView: self.view) { make in
            make.left.right.equalTo(0)
            make.top.equalTo(self.navigationView.snp.bottom).offset(0)
            make.height.equalTo(devWidthRatio*88)
            
        }
        return v
    }()
    
    private lazy var card:UIImageView  = {
        let v = create_imageView(image: IMAGE("cardicon"), mode: .scaleAspectFill, supView: self.view) { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(devWidthRatio*256)
            make.top.equalTo(self.topView.snp.bottom).offset(devWidthRatio*38)
            make.height.equalTo(devWidthRatio*168)
        }
        v.layer.masksToBounds = true
        v.layer.cornerRadius = 16
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        v.isUserInteractionEnabled = true
        v.addGestureRecognizer(tap)
        return v
    }()
    private lazy var donea:UIImageView  = {
        let v = create_imageView(image: IMAGE("icon_right"), mode: .scaleToFill, supView: self.card) { make in
            make.width.height.equalTo(24)
            make.right.bottom.equalTo(-10)
        }
        v.isHidden = true
        return v
    }()
    
    
    
    private lazy var face:UIImageView  = {
        let v = create_imageView(image: IMAGE("faceicon"), mode: .scaleAspectFill, supView: self.view) { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(devWidthRatio*256)
            make.top.equalTo(self.card.snp.bottom).offset(devWidthRatio*51)
            make.height.equalTo(devWidthRatio*168)
        }
        v.layer.masksToBounds = true
        v.layer.cornerRadius = 16
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapAction))
        v.isUserInteractionEnabled = true
        v.addGestureRecognizer(tap)
        return v
    }()
    private lazy var doneb:UIImageView  = {
        let v = create_imageView(image: IMAGE("icon_right"), mode: .scaleToFill, supView: self.face) { make in
            make.width.height.equalTo(24)
            make.right.bottom.equalTo(-10)
        }
        v.isHidden = true
        return v
    }()
    private lazy var nextButton:UIButton = {
        let v = create_button(title: "Next", titleColor: rgba(hex: "#FFFFFF"),titleFont: SLFontConfig.medium(size: 15),bgColor: rgba(hex: "#1608EC"), image: nil, supView: self.view, closure: { make in
            make.left.equalTo(47)
            make.right.equalTo(-47)
            make.bottom.equalTo(-12-DevConfig.safe_bottom)
            make.height.equalTo(44)
        }, selector: (target: self, action: #selector(nextClick), event:.touchUpInside))
        v.layer.masksToBounds = true
        v.layer.cornerRadius = 22
        return v
    }()
    @objc private func nextClick(){
        let awards1 = self.json!["characters"]["arrows"].intValue
        let awards2 = self.json!["shinto"]["arrows"].intValue
        if awards1 != 1{
            type = 0
            cardAction()
            return
        }else if awards2 != 1{
            type = 1
            cameraAuthorized()
            return
        }
        self.navigationController?.popViewController(animated: true)
    }
    
    func loadData(){
        let mbp = MBProgressHUD.showMessage(message: "")
        SLHttpTool.AsyncReportData(path: "/satisfies/face",params: ["sources":self.id], target: self) { responseCall, success, msg, code in
            mbp.hide(animated: false)
            if success {
                self.json = responseCall["wavelets"]
                if self.json != nil{
                    let cardArrow = self.json!["characters"]["arrows"].intValue
                    if cardArrow == 1 {
                        self.denotes = self.json!["characters"]["denotes"].stringValue
                        self.haveCard = true
                        self.donea.isHidden = false
                    }
                    let faceArrow = self.json!["shinto"]["arrows"].intValue
                    if faceArrow == 1 {
                        self.doneb.isHidden = false
                    }
                    let cardurl = self.json!["characters"]["imitate"].stringValue
                    self.card.setUrlImage(url: cardurl, placeholder: IMAGE("cardicon"))
                    let faceurl = self.json!["shinto"]["imitate"].stringValue
                    self.face.setUrlImage(url: faceurl, placeholder: IMAGE("faceicon"))
                }
            }else{
                MBProgressHUD.showError(error: msg)
            }
        }
    }
    func cardAction(){
        self.guideTime1 = Int(Date().timeIntervalSince1970)
        SLIdTypeSlectVC.showAlert(page: self, id: self.id) {[weak self] value in
            if let ss = self {
                SLHttpTool.AsyncUploadData(mahathat:"2",extended:ss.json!["doorstep"]["tiered"].stringValue, thais: "\(ss.guideTime1)", target: self) { responseCall, success, msg, code in}
                
                DispatchQueue.main.async {
                    ss.guideTime2 = Int(Date().timeIntervalSince1970)
                    ss.denotes = value as? String
                    ss.type = 0
                    SLIdentificationTooltip.showAlert(page: ss, type: .card) { tag in
                        ss.showPick()
                    }
                }
                
            }
            
        }
    }
    
    func cameraAuthorized()  {
        let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
        if authStatus == .authorized{self.showCamera()}
        if authStatus == .denied{self.showPhotoServicesDeniedAlert()}
        if authStatus == .notDetermined {
            AVCaptureDevice.requestAccess(for: .video) { granted in
                if granted{
                    self.showCamera()
                }
            }
        }
    }
    // 弹出警告，引导用户到设置去开启相机权限
     func showPhotoServicesDeniedAlert() {
        let alertController = UIAlertController(
            title: "The Camera is closed",
            message: "Authorize camera access to easily take ID card photos and have a convenient operation process.",
            preferredStyle: .alert)
        
        alertController.addAction(UIAlertAction(title: "cancel", style: .cancel, handler: { _ in}))
        
        alertController.addAction(UIAlertAction(title: "setting", style: .default, handler: { _ in
            if let appSettings = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(appSettings, options: [:]) { _ in
                }
            }
        }))
        self.present(alertController, animated: true, completion: nil)
    }
    func updateUI(){
        self.nextButton.isHidden = false
        
    }

    @objc private func tapAction(_ sender: UITapGestureRecognizer) {
        if sender.view == self.card{
            self.type = 0
            self.cardAction()
        }else if sender.view == self.face{
            self.type = 1
            self.faceAction()
        }
    }
    func faceAction(){
        if !self.haveCard {
            MBProgressHUD.showError(error: "Please upload your ID card first")
            return
        }
        DispatchQueue.main.async {
            self.guideTime3 = Int(Date().timeIntervalSince1970)
            SLIdentificationTooltip.showAlert(page: self, type: .face) { [weak self] tag in
                guard let self = self else { return  }
                self.showPickerController(type: .camera, camera: .front)
            }
        }
    }
    func showCamera(){
        let arrows1 = self.json!["characters"]["arrows"].intValue
        let arrows2 = self.json!["shinto"]["arrows"].intValue

        DispatchQueue.main.async {
            if self.type == 0 {
                if arrows1 == 1 {return}
                self.type = 0
                self.cardAction()
            }else if self.type == 1 {
                if arrows2 == 1 {return}
                self.type = 1
                self.faceAction()
            }

        }
    }
    func showPick(){
        let alert = UIAlertController(title: "", message: nil, preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {[weak self] action in
            self?.showCamera(type: .camera)
        }))
        alert.addAction(UIAlertAction(title: "Photo", style: .default, handler: {[weak self] action in
            self?.showCamera(type: .photoLibrary)
        }))
        present(alert, animated: true, completion: nil)
    }
    func showCamera(type:UIImagePickerController.SourceType){
        if type == .camera {
            let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
            if authStatus == .authorized{self.showPickerController(type: type)}
            if authStatus == .denied{self.showPhotoServicesDeniedAlert()}
            if authStatus == .notDetermined {
                AVCaptureDevice.requestAccess(for: .video) { granted in
                    if granted{
                        self.showPickerController(type: type)
                    }
                }
            }
        }else{
            self.showPickerController(type: type)
        }
        
       
    }
    func showPickerController(type:UIImagePickerController.SourceType,camera:UIImagePickerController.CameraDevice = .rear){
        DispatchQueue.main.async {
            //创建图片控制器
            let  picker =  UIImagePickerController ()
            //设置代理
            picker.delegate =  self
            //设置来源
            picker.sourceType = type
            //允许编辑
            picker.allowsEditing =  false
            if type == .camera{
                picker.cameraDevice = camera
            }
            
            self.present(picker, animated:  true , completion: { () ->  Void  in
            })
        }
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
           print("------> INFO:\(info)")

        if let image = info[.originalImage] as? UIImage{
            if self.type == 1 {
                self.uploadImage(image: image, isCard: false)
            }else{
                self.uploadImage(image: image, isCard: true)
            }
        }
           picker.dismiss(animated: true, completion: nil)
       }

    func uploadImage(image: UIImage,isCard:Bool){

        let ysimage = Helper.compressImage(image, toByte: 1024*1024)
        var params:[String: String] = [:]
        params["denotes"] = self.denotes
        if isCard {
            params["transmitted"] = "2"
            params["transfer"] = "11"
        }else{
            params["transmitted"] = "1"
            params["transfer"] = "10"
        }
        let mbp = MBProgressHUD.showMessage(message: "")
        if isCard {
            SLHttpTool.AsyncReportData(path: "/satisfies/flush",params: params,image: ysimage, fileName: "narrowMegalithic", target: self) { responseCall, success, msg, code in
                mbp.hide(animated: false)
                if success {
                    SLHttpTool.AsyncUploadData(mahathat:"3",extended:self.json!["doorstep"]["tiered"].stringValue, thais: "\(self.guideTime2)", target: self) { responseCall, success, msg, code in
                    }
                    let derivatives = responseCall["wavelets"]["derivatives"].arrayValue
                    if derivatives.count > 0 {
                        SLInfoAffirmTip.showAlert(page: self, json: responseCall["wavelets"],denotes: self.denotes!) { value in
                            self.loadData()
                        }
                    }else{
                        self.loadData()
                    }
                    
                    }else{
                        MBProgressHUD.showError(error: msg)
                    }
                }
        }else{
            
            SLHttpTool.AsyncReportData(path: "/satisfies/flush",params: params,image: ysimage,fileName:"narrowMegalithic", target: self) { responseCall, success, msg, code in
                mbp.hide(animated: true)
                self.loadData()
                if success {
                    SLHttpTool.AsyncUploadData(mahathat:"4",extended:self.json!["doorstep"]["tiered"].stringValue, thais: "\(self.guideTime3)", target: self) { responseCall, success, msg, code in
                    }
                }else{
                    MBProgressHUD.showError(error: msg)
                }
            }
        }
    }
}
